<template>
  <div class="ele-body">
    <el-card shadow="never">
      <!-- 搜索表单 -->
      <el-form :model="where" class="ele-form-search" label-width="77px" @keyup.enter.native="reload"
               @submit.native.prevent>
        <el-row :gutter="15">
          <el-col :lg="6" :md="12">
            <el-form-item label="出厂编号:">
              <el-input v-model="where.name" clearable placeholder="请输入出厂编号"/>
            </el-form-item>
          </el-col>
          <el-col :lg="6" :md="12">
            <div class="ele-form-actions">
              <el-button v-if="permission.includes('sys:product:index')" class="ele-btn-icon" icon="el-icon-search"
                         type="primary" @click="reload">
                查询
              </el-button>
              <el-button @click="reset">重置</el-button>
            </div>
          </el-col>
        </el-row>
      </el-form>
      <!-- 数据表格 -->
      <ele-pro-table ref="table" :columns="columns" :datasource="url" :selection.sync="selection" :where="where"
                     height="calc(100vh - 315px)">
        <!-- 表头工具栏 -->
        <template slot="toolbar">
          <el-button v-if="permission.includes('sys:product:add')" class="ele-btn-icon" icon="el-icon-plus" size="small"
                     type="primary" @click="openEdit(null)">
            添加
          </el-button>

          <div class="exportBtn" v-loading="exportFlag" v-if="permission.includes('sys:product:export')">
            <download-excel
              class="export-excel-wrapper"
              :data="selection"
              :fields="json_fields"
              :header="title"
              :before-generate="startDownload"
              :before-finish="finishDownload"
              name="产品.xls"
            >
              <el-button size="small" type="primary" :disabled="selection.length==0">
                导出
              </el-button>
            </download-excel>
          </div>
          <div class="exportBtn">
            <el-button v-if="permission.includes('sys:product:export')" type="primary" class="ele-btn-icon" size="small"
                       @click="exportAll" :loading="exportAllLoading">
              导出全部
            </el-button>
          </div>
          <div class="exportBtn">
            <el-button icon="el-icon-download" type="primary"
                       class="ele-btn-icon" size="small" @click="downloadModel">
              下载模板
            </el-button>
          </div>
          <div class="exportBtn">
            <el-button icon="el-icon-upload2" v-if="permission.includes('sys:product:import')" type="primary"
                       class="ele-btn-icon"
                       size="small" @click="importAll">
              导入
            </el-button>
          </div>
        </template>
        <template slot="product_number" slot-scope="{row}">
          <div style="color: var(--color-primary);cursor: pointer;"
               @click="$router.push('/product/product/info?id=' + row.id)">
            {{ row.product_number }}
          </div>
        </template>
        <template slot="qrcode" slot-scope="{row}">
          <div v-show="row.qrcode ? row.qrcode.status_title === '已关联' : ''"
               style=" color: rgb(37, 99, 235);cursor: pointer;" @click="showQrcode(row.qrcode.url, row.qrcode.id)">
            {{ row.qrcode ? row.qrcode.status_title : "" }}
          </div>
          <div v-show="row.qrcode === null" style="color: rgb(37, 99, 235);cursor: pointer;" @click="openCodeEdit(row)">
            未关联
          </div>
        </template>
        <!-- 操作列 -->
        <template slot="action" slot-scope="{row}">
          <el-link v-if="permission.includes('sys:product:edit')" :underline="false" icon="el-icon-edit" type="primary"
                   @click="openEdit(row)">
            修改
          </el-link>
          <el-popconfirm class="ele-action" title="确定要删除此产品吗？" @confirm="remove(row)">
            <el-link v-show="permission.includes('sys:product:delete')" slot="reference" :underline="false"
                     icon="el-icon-delete" type="danger">
              删除
            </el-link>
          </el-popconfirm>
        </template>
      </ele-pro-table>
    </el-card>
    <product-form ref="productFormRef" @reload="reload"/>
    <show-qrcode ref="showQrcode" @putQrcode="putQrcode"/>
    <edit-code ref="CodeEdit" :visible.sync="codeEdit" @editQrCode="editQrCode"/>
    <importData :visible.sync="showImport" @done="completeImport" type="product"></importData>


  </div>
</template>

<script>
import {mapGetters} from "vuex";
import ShowQrcode from "./compenents/show-qrcode.vue"
import EditCode from "./compenents/code-edit.vue"
import ProductForm from "@/views/product/product/compenents/product-form.vue";
import importData from "@/components/importData.vue";

export default {
  name: 'SystemLevel',
  components: {
    ProductForm,
    ShowQrcode,
    EditCode,
    importData,
  },
  computed: {
    ...mapGetters(["permission"]),
  },
  data() {
    return {
      exportFlag: false,
      title: "产品信息",
      json_fields: {
        "客户编号": 'customer.customer_number',
        "客户": 'customer.name',
        "型号": 'type.name',
        "出厂编号": 'name',
        "购买日期（质保起始日期）": 'date_buy',
        "安装地址/项目地址": 'install_address',
        "质保开始日期": 'warranty_start_date',
        "质保结束日期": 'warranty_end_date',
      },
      // 表格数据接口
      url: '/products',
      // 表格列配置
      columns: [
        {
          columnKey: 'selection',
          type: 'selection',
          width: 45,
          align: 'center',
          fixed: "left"
        },
        {
          prop: 'product_number',
          label: '编号',
          width: 150,
          align: 'center',
          slot: 'product_number',
        },
        {
          prop: 'name',
          label: '出厂编号',
          showOverflowTooltip: true,
          minWidth: 120,
          align: 'center',
        },
        {
          prop: 'customer.name',
          label: '客户',
          align: 'center',
          width: 200,
        },
        {
          prop: 'type.name',
          label: '设备型号',
          showOverflowTooltip: true,
          minWidth: 150,
          align: 'center'
        },
        {
          prop: 'warranty_start',
          label: '质保开始日期',
          showOverflowTooltip: true,
          minWidth: 160,
          align: 'center'
        },
        {
          prop: 'warranty_end',
          label: '质保结束日期',
          showOverflowTooltip: true,
          minWidth: 160,
          align: 'center'
        },
        {
          prop: 'warranty_status_title',
          label: '质保状态',
          showOverflowTooltip: true,
          minWidth: 150,
          align: 'center'
        },
        {
          prop: 'create_user.realname',
          label: '创建人',
          showOverflowTooltip: true,
          minWidth: 100,
          align: 'center'
        },
        {
          prop: 'create_time_format',
          label: '创建时间',
          showOverflowTooltip: true,
          minWidth: 160,
          align: 'center'
        },
        {
          prop: 'qrcode',
          label: '二维码',
          showOverflowTooltip: true,
          minWidth: 160,
          align: 'center',
          slot: 'qrcode',
        },
        {
          columnKey: 'action',
          label: '操作',
          width: 150,
          align: 'center',
          resizable: false,
          slot: 'action',
          fixed: "right"
        }
      ],
      // 表格搜索条件
      where: {},
      // 表格选中数据
      selection: [],
      // 当前编辑数据
      current: null,
      // 是否显示编辑弹窗
      showEdit: false,
      // 二维码是否显示编辑弹窗
      codeEdit: false,
      // 当前编辑数据
      currentCode: null,
      // 是否显示导入弹窗
      showImport: false,
      exportAllLoading: false,
      model: '#'
    };
  },
  mounted() {
    this.getModel()
  },
  methods: {
    getModel() {
      this.$http.get('/template/product').then((res) => {
        this.model = res.data.data
        //聚焦刷新
        this.$forceUpdate()
      })

    },
    downloadModel() {
      window.open(this.model, '_self');
    },
    startDownload() {
      if (this.selection.length === 0)
        return false
      this.exportFlag = true
    },
    finishDownload() {
      console.log(2222)
      this.exportFlag = false
    },
    /*导入*/
    importAll() {
      this.showImport = true
    },
    completeImport() {
      this.showImport = false
      this.reload()
    },
    /*导出全部*/
    exportAll() {
      this.exportAllLoading = true
      this.$http.get('products_export').then(res => {
        if (res.data.code === 0) {
          this.exportAllLoading = false
          this.$message.success(res.data.msg);
          const link = document.createElement('a')
          link.href = res.data.data.url
          document.body.appendChild(link)
          link.click()
          document.body.removeChild(link)
        } else {
          this.exportAllLoading = false
          this.$message.error(res.data.msg);
        }
      }).catch(e => {
        this.$message.error(e.message);
      });
    },
    // 编辑产品二维码
    openCodeEdit(row) {
      this.$refs.CodeEdit.product_id = row.id;
      this.codeEdit = true;
    },
    editQrCode(value, id) {
      const loading = this.$loading({lock: true});
      this.$http.put('/qr_code/' + id, {product_id: value}).then(res => {
        loading.close();
        if (res.data.code === 0) {
          this.$message.success(res.data.msg);
          this.$refs.CodeEdit.code_name = "";
          this.$refs.CodeEdit.updateVisible(false);
          loading.close()
          this.reload();
        } else {
          this.$message.error(res.data.msg);
        }
      }).catch(e => {
        loading.close();
        this.$message.error(e.message);
      });
    },
    /* 刷新表格 */
    reload() {
      this.$refs.table.reload({where: this.where});
    },
    /* 重置搜索 */
    reset() {
      this.where = {};
      this.reload();
    },
    /* 显示编辑 */
    openEdit(row) {
      this.$refs.productFormRef.showDialog(row ? "edit" : "add", row);
      this.$forceUpdate()

    },
    /* 删除 */
    remove(row) {
      const loading = this.$loading({lock: true});
      this.$http.delete('/products/' + row.id).then(res => {
        loading.close();
        if (res.data.code === 0) {
          this.$message.success(res.data.msg);
          this.reload();
        } else {
          this.$message.error(res.data.msg);
        }
      }).catch(e => {
        loading.close();
        this.$message.error(e.message);
      });
    },
    // 显示二维码
    showQrcode(url, id) {
      this.$refs.showQrcode.dialogVisible = true;
      this.$refs.showQrcode.url = url;
      this.$refs.showQrcode.id = id;
    },
    putQrcode(id) {
      this.$http.put("/qr_code/" + id, {product_id: 0}).then(res => {
        this.$message({type: "success", message: res.data.msg})
        this.$refs.showQrcode.dialogVisible = false;
        this.reload();
      })
    }
  }
}
</script>

<style scoped>
.exportBtn {
  margin-left: 10px;
}

.el-autocomplete {
  width: 100%;
}

.el-input {
  width: 100% !important;
}
</style>
